package com.aqadoos.restservice;

import com.aqadoos.domain.Department;
import com.aqadoos.service.DepartmentService;
import flexjson.JSONSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.List;

@Path("/dept")
@Component
@Scope("prototype")
public class DepartmentRestService {		

	// Allows to insert contextual objects into the class,
	// e.g. ServletContext, Request, Response, UriInfo
	@Context
	private UriInfo uriInfo;
	@Context
	private Request request;
	
	@Autowired
	private DepartmentService departmentService;

	@POST
	@Path("/create")
    @Consumes(MediaType.APPLICATION_JSON)
	public Response create(Department department) {
        long newDeptId = departmentService.create(department);
        String response = "{deptId:" + newDeptId + "}";
        return Response.status(201).entity(response).build();
	}

	@GET
	@Path("/findById/{deptId}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response findById(@PathParam("deptId")String id) {
		Department department = departmentService.findById(Long.parseLong(id));
        JSONSerializer jsonSerializer = new JSONSerializer();
        String deptJson = jsonSerializer.serialize(department);
        return Response.status(201).entity(deptJson).build();
	}

	@GET
	@Path("/findAll")
	@Produces(MediaType.APPLICATION_JSON)
	public Response findAll() {
		List<Department> departments = departmentService.findAll();
        JSONSerializer jsonSerializer = new JSONSerializer();
        String deptsJson = jsonSerializer.serialize(departments);
        return Response.status(201).entity(jsonSerializer.serialize(deptsJson)).build();
	}
}
